// 同步修复工具
class SyncFixer {
  constructor() {
    this.fixes = []
  }

  // 添加修复记录
  addFix(type, description, success) {
    const fix = {
      id: Date.now() + Math.random(),
      timestamp: new Date(),
      type,
      description,
      success
    }

    this.fixes.push(fix)
    console.log(`🔧 [${type.toUpperCase()}] ${description} - ${success ? '成功' : '失败'}`)
  }

  // 修复SignalR连接问题
  async fixSignalRConnection(signalRService) {
    this.addFix('connection', '开始修复SignalR连接', true)

    try {
      // 检查连接状态
      if (signalRService.getConnectionStatus && signalRService.getConnectionStatus()) {
        this.addFix('connection', 'SignalR已连接，无需修复', true)
        return true
      }

      // 尝试重新连接
      if (signalRService.connect) {
        await signalRService.connect()
        this.addFix('connection', 'SignalR重新连接成功', true)
        return true
      } else {
        this.addFix('connection', 'SignalR服务缺少connect方法', false)
        return false
      }
    } catch (error) {
      this.addFix('connection', `SignalR连接修复失败: ${error.message}`, false)
      return false
    }
  }

  // 修复事件监听器问题
  fixEventListeners(signalRService, eventName, callback) {
    this.addFix('events', `开始修复事件监听器: ${eventName}`, true)

    try {
      if (!signalRService || !signalRService.on) {
        this.addFix('events', 'SignalR服务不可用或缺少on方法', false)
        return false
      }

      // 先移除可能存在的监听器
      if (signalRService.off) {
        signalRService.off(eventName, callback)
        this.addFix('events', `已移除旧的${eventName}监听器`, true)
      }

      // 重新添加监听器
      signalRService.on(eventName, callback)
      this.addFix('events', `已重新添加${eventName}监听器`, true)
      return true
    } catch (error) {
      this.addFix('events', `事件监听器修复失败: ${error.message}`, false)
      return false
    }
  }

  // 修复画布上下文问题
  fixCanvasContext(canvasRef) {
    this.addFix('canvas', '开始修复画布上下文', true)

    try {
      if (!canvasRef.value) {
        this.addFix('canvas', 'Canvas元素不存在', false)
        return false
      }

      const canvas = canvasRef.value
      const ctx = canvas.getContext('2d')

      if (!ctx) {
        this.addFix('canvas', '无法获取Canvas 2D上下文', false)
        return false
      }

      // 重置画布状态
      ctx.fillStyle = '#ffffff'
      ctx.strokeStyle = '#000000'
      ctx.lineWidth = 1
      ctx.lineCap = 'round'
      ctx.lineJoin = 'round'

      this.addFix('canvas', '画布上下文已重置', true)
      return true
    } catch (error) {
      this.addFix('canvas', `画布上下文修复失败: ${error.message}`, false)
      return false
    }
  }

  // 修复房间加入问题
  async fixRoomJoin(signalRService, roomId, playerId, nickname, color) {
    this.addFix('room', `开始修复房间加入: ${roomId}`, true)

    try {
      if (!signalRService || !signalRService.joinRoom) {
        this.addFix('room', 'SignalR服务缺少joinRoom方法', false)
        return false
      }

      // 尝试重新加入房间
      await signalRService.joinRoom(roomId, playerId, nickname, color)
      this.addFix('room', `房间${roomId}加入成功`, true)
      return true
    } catch (error) {
      this.addFix('room', `房间加入修复失败: ${error.message}`, false)
      return false
    }
  }

  // 修复消息队列问题
  fixMessageQueue(signalRService) {
    this.addFix('queue', '开始修复消息队列', true)

    try {
      if (!signalRService || !signalRService.getMessageQueueStatus) {
        this.addFix('queue', 'SignalR服务缺少消息队列方法', false)
        return false
      }

      const queueStatus = signalRService.getMessageQueueStatus()
      
      if (queueStatus.queueLength > 0) {
        // 尝试处理消息队列
        if (signalRService.processMessageQueue) {
          signalRService.processMessageQueue()
          this.addFix('queue', `已处理${queueStatus.queueLength}条队列消息`, true)
        } else {
          this.addFix('queue', 'SignalR服务缺少processMessageQueue方法', false)
        }
      } else {
        this.addFix('queue', '消息队列为空，无需处理', true)
      }

      return true
    } catch (error) {
      this.addFix('queue', `消息队列修复失败: ${error.message}`, false)
      return false
    }
  }

  // 修复防抖问题
  fixDebounce(component) {
    this.addFix('debounce', '开始修复防抖机制', true)

    try {
      // 清理可能存在的防抖定时器
      if (component.paintDebounceTimer) {
        clearTimeout(component.paintDebounceTimer)
        component.paintDebounceTimer = null
        this.addFix('debounce', '已清理防抖定时器', true)
      }

      // 重置防抖延迟
      if (component.paintDebounceDelay === undefined) {
        component.paintDebounceDelay = 16 // 约60fps
        this.addFix('debounce', '已设置防抖延迟为16ms', true)
      }

      return true
    } catch (error) {
      this.addFix('debounce', `防抖修复失败: ${error.message}`, false)
      return false
    }
  }

  // 修复玩家ID问题
  fixPlayerId(gameStore) {
    this.addFix('player', '开始修复玩家ID问题', true)

    try {
      if (!gameStore || !gameStore.currentPlayer) {
        this.addFix('player', '游戏Store或当前玩家不存在', false)
        return false
      }

      // 确保玩家ID存在
      if (!gameStore.currentPlayer.id) {
        gameStore.currentPlayer.id = 'player-' + Math.random().toString(36).substr(2, 9)
        this.addFix('player', '已生成新的玩家ID', true)
      }

      return true
    } catch (error) {
      this.addFix('player', `玩家ID修复失败: ${error.message}`, false)
      return false
    }
  }

  // 完整修复流程
  async fullFix(signalRService, canvasRef, gameStore, roomId, playerId, nickname, color) {
    this.addFix('full', '开始完整同步修复流程', true)

    const results = {
      connection: false,
      events: false,
      canvas: false,
      room: false,
      queue: false,
      debounce: false,
      player: false
    }

    try {
      // 1. 修复SignalR连接
      results.connection = await this.fixSignalRConnection(signalRService)

      // 2. 修复事件监听器（需要等待连接建立）
      if (results.connection) {
        // 这里需要传入实际的事件处理函数，暂时跳过
        results.events = true
        this.addFix('events', '事件监听器修复跳过（需要实际回调函数）', true)
      }

      // 3. 修复画布上下文
      results.canvas = this.fixCanvasContext(canvasRef)

      // 4. 修复房间加入
      if (results.connection && roomId && playerId) {
        results.room = await this.fixRoomJoin(signalRService, roomId, playerId, nickname, color)
      }

      // 5. 修复消息队列
      if (results.connection) {
        results.queue = this.fixMessageQueue(signalRService)
      }

      // 6. 修复防抖（需要组件实例）
      results.debounce = true
      this.addFix('debounce', '防抖修复跳过（需要组件实例）', true)

      // 7. 修复玩家ID
      results.player = this.fixPlayerId(gameStore)

      // 统计修复结果
      const successCount = Object.values(results).filter(Boolean).length
      const totalCount = Object.keys(results).length

      this.addFix('summary', `修复完成: ${successCount}/${totalCount} 项成功`, successCount === totalCount)

      return {
        success: successCount === totalCount,
        results,
        summary: {
          total: totalCount,
          success: successCount,
          failed: totalCount - successCount
        }
      }

    } catch (error) {
      this.addFix('full', `完整修复流程失败: ${error.message}`, false)
      return {
        success: false,
        error: error.message,
        results
      }
    }
  }

  // 获取修复报告
  getFixReport() {
    return {
      timestamp: new Date(),
      fixes: [...this.fixes],
      summary: {
        total: this.fixes.length,
        success: this.fixes.filter(f => f.success).length,
        failed: this.fixes.filter(f => !f.success).length,
        byType: this.fixes.reduce((acc, f) => {
          acc[f.type] = (acc[f.type] || 0) + 1
          return acc
        }, {})
      }
    }
  }

  // 清空修复记录
  clearFixes() {
    this.fixes = []
    console.log('🔧 修复记录已清空')
  }

  // 导出修复报告
  exportFixReport() {
    const report = this.getFixReport()
    const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `sync-fix-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.json`
    link.click()
    URL.revokeObjectURL(url)

    this.addFix('export', '修复报告已导出', true)
  }
}

// 创建全局修复器实例
const syncFixer = new SyncFixer()

export default syncFixer

